package gao.xiaolei.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import javax.annotation.Resource;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.SAXException;
import gao.xiaolei.excepition.MyExcepition;
import gao.xiaolei.util.FileManage;
import gao.xiaolei.util.Jgit;
import gao.xiaolei.util.ReadFile;

@RestController
@CrossOrigin
@RefreshScope
public class ConfigController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private Environment env;

    @Resource(name = "Jgit")
    private Jgit jgit;

    @Value("${gitConfig.localPath}")
    private String defaultGitPath;
    @Value("${fileConfig.defaultGitName}")
    private String defaultGitName;//本地仓库名
    @Value("${eureka.client.serviceUrl.defaultZone}" + "apps")
    private String defaultEurakaUrl;
    @Value("${fileConfig.defaultFilePath}")
    private String defaultFilePath;
    @Value("${fileConfig.suffix}")
    private String suffix;//配置文件-后面的字符

    public String getDefaultGitPath() {
        return defaultGitPath;
    }

    public void setDefaultGitPath(String defaultGitPath) {
        this.defaultGitPath = defaultGitPath;
    }

    public String getDefaultGitName() {
        return defaultGitName;
    }

    public void setDefaultGitName(String defaultGitName) {
        this.defaultGitName = defaultGitName;
    }

    public String getDefaultEurakaUrl() {
        return defaultEurakaUrl;
    }

    public void setDefaultEurakaUrl(String defaultEurakaUrl) {
        this.defaultEurakaUrl = defaultEurakaUrl;
    }

    public String getDefaultFilePath() {
        return defaultFilePath;
    }

    public void setDefaultFilePath(String defaultFilePath) {
        this.defaultFilePath = defaultFilePath;
    }

    @GetMapping(value = "/getAllServerName")
    public List<String> getAllServerName() {
        List<String> names = null;
        try {
            names = ReadFile.readServiceName(defaultEurakaUrl);
            names.add(0, "application");
        } catch (ParserConfigurationException | SAXException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return names;
    }

    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam(name = "file", required = true) MultipartFile file) throws GitAPIException, IOException {
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('/') + 1);
        if (jgit.isHave(defaultGitName))
            jgit.pull(defaultGitName, "master", defaultGitName);
        else
            jgit.clone(defaultGitName, defaultGitName);
        FileManage.fileUpload(defaultGitPath + "/" + defaultGitName + "/" + defaultFilePath + "/" + fileName, file);
        jgit.add(defaultGitName, defaultFilePath + "/" + fileName);
        jgit.commit(defaultGitName, "更新" + fileName);
        jgit.push(defaultGitName, "master", defaultGitName);
        return "上传成功";
    }

    @GetMapping(value = "/fileDownload")
    public ResponseEntity<byte[]> fileDownload(@RequestParam(name = "fileName", required = true) String fileName) throws MyExcepition, GitAPIException, IOException {
        byte[] fileByte = null;
        if (jgit.isHave(defaultGitName))
            jgit.pull(defaultGitName, "master", defaultGitName);
        else
            jgit.clone(defaultGitName, defaultGitName);
        String fileRealName = "application".equals(fileName) ? "application.yml" : fileName.concat("-").concat(suffix).concat(".yml");
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>(1);
        header.add("content-disposition", "attachment;filename=" + URLEncoder.encode(fileRealName, "UTF-8"));
        fileByte = FileManage.fileDownload(defaultGitPath + "/" + defaultGitName + "/" + defaultFilePath + "/".concat(fileRealName));
        return new ResponseEntity<byte[]>(fileByte, header, HttpStatus.OK);
    }

    @PostMapping(value = "/refreshClient")
    public void refreshClient(@RequestParam(name = "serviceName", required = true) String serviceName) {
        if (!"application".equals(serviceName)) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);//不知道为什么一定要这个json的Content-Type,不然就会报415
            HttpEntity<String> formEntity = new HttpEntity<String>(headers);
            restTemplate.postForEntity("http://training-rabbitmq/actuator/bus-refresh/".concat(serviceName).concat(":**"), formEntity, String.class);
        } else {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> formEntity = new HttpEntity<String>(headers);//不知道为什么一定要这个json的Content-Type,不然就会报415
            restTemplate.postForObject("http://training-rabbitmq/actuator/bus-refresh", formEntity, String.class);
        }
    }
}
